<template>
  <div>
    <el-drawer
      :title="!dataForm.id ? '新增' : '修改'"
      :visible="visible"
      size="90vw"
      @close="closeDialog"
      append-to-body
    >
      <div style="margin: 20px 40px">
        <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        label-width="100px">
          <el-collapse v-model="activeNames">
            <el-collapse-item name="1">
              <template slot="title">
                <div>
                  <i class="header-icon el-icon-goods"></i>
                  <span class="title-size">基本信息</span>
                </div>
              </template>
              <el-row style="margin-top:20px">
                <el-col :span="12">
                  <el-form-item label="商品标题" prop="spuTitle">
                    <el-input v-model="dataForm.spuTitle" placeholder="商品标题" ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商品品牌" prop="brandId">
                    <el-select
                      v-model="dataForm.brandId"
                      filterable
                      placeholder="请选择商品品牌"
                      clearable
                      style="width:100%"
                    >
                      <el-option
                        v-for="dict in brandList"
                        :key="dict.id"
                        :label="dict.brandName"
                        :value="dict.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="商品副标题" prop="spuSubTitle">
                    <el-input v-model="dataForm.spuSubTitle" placeholder="商品副标题" ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="上架状态" prop="status">
                    <el-switch v-model="dataForm.status" active-value="1" inactive-value="0" @change="handleChangeGoodsSpuStatus"></el-switch>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="商品标签" prop="sort">
                    <el-select v-model="dataForm.goodsLabelIds" multiple placeholder="请选择" style="width:100%">
                      <el-option
                        v-for="item in goodsLabelList"
                        :key="item.id"
                        :label="item.labelName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="dataForm.sort" controls-position="right" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="goodsServerList.length > 0">
                <el-row>
                  <el-form-item label="保障服务" prop="goodsServerIds">
                    <el-checkbox-group v-model="dataForm.goodsServerIds">
                      <el-checkbox :label="item.id" v-for="(item, index) in goodsServerList" :key="index">{{item.serverName}}</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-row>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="商品类型" prop="spuType">
                    <el-radio-group v-model="dataForm.spuType" style="width:300px">
                      <el-radio label="1" style="margin-right:10px" border>普通</el-radio>
                      <el-radio label="2" style="margin-right:10px" border>内购</el-radio>
                      <el-radio label="3" style="margin-right:10px" border>隐藏</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="活动结束日期" prop="activityEndDate">
                    <el-date-picker
                      v-model="dataForm.activityEndDate"
                      type="date"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="请选择活动结束日期"
                      clearable
                      style="width: 100%;">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- <el-form-item label="商品图片" prop="brandName">
                  <ImagesUpload></ImagesUpload>
              </el-form-item>
              <el-form-item label="商品名称" prop="goodsName">
                <el-input v-model="dataForm.goodsName" placeholder="商品名称" ></el-input>
              </el-form-item> -->
            </el-collapse-item>
            <el-collapse-item name="2">
              <template slot="title">
                <div>
                  <i class="header-icon el-icon-s-order"></i>
                  <span class="title-size">规格信息</span>
                </div>
              </template>
              <div style="padding:20px">
                <el-tabs type="border-card">
                  <el-tab-pane label="商品规格">
                    <div v-if="goodsSpuSpecList.length > 0">
                      <div v-for="(spec, index) in goodsSpuSpecList" :key="index" style="margin-bottom:20px">
                        <el-row class="border-buttom" style="padding:5px">
                          <el-col :span="23">
                            {{spec.value}}
                          </el-col>
                          <el-col :span="1" style="display: flex;justify-content: right;">
                            <el-link :underline="false" type="danger" @click="handleDelSpec(spec)">
                              <span style="font-size:12px">移除</span>
                            </el-link>
                          </el-col>
                        </el-row>
                        <el-row>
                          <div style="padding:5px; margin: 10px 0px">
                            <el-tag
                              v-for="tag in spec.leaf"
                              :key="tag.specId"
                              closable
                              style="margin-right:10px"
                              @close="handleTagClose(spec,tag)">
                              {{tag.value}}
                            </el-tag>
                          </div>
                          <el-popover
                            placement="bottom"
                            width="160"
                            v-model="spec.isShowSpecValue"
                            @show="handleShowSpecValue(spec)">
                            <el-select
                              v-model="selectedSpecValue"
                              filterable
                              placeholder="请选择规格值"
                              clearable
                              style="width:100%"
                              @change="handleShowSpecValueChange(spec, $event)"
                            >
                              <el-option
                                v-for="dict in spec.goodsSpecValueList"
                                :key="dict.id"
                                :label="dict.name"
                                :value="dict.id"
                                :disabled="dict.disabled"
                              />
                            </el-select>
                            
                          
                            <el-link :underline="false" slot="reference" type="primary">
                              <span style="font-size:12px">添加规格值</span>
                            </el-link>
                          </el-popover>
                        </el-row>
                      </div>
                    </div>

                    <div v-else style="display: flex;justify-content: center;margin:10px 0px">
                      <span style="opacity: 0.5;">暂无数据</span>
                    </div>

                    <el-row style="display: flex;justify-content: center;">
                      <el-popover
                        placement="bottom"
                        width="160"
                        v-model="isShowSpec">
                        <el-select
                          v-model="selectedSpec"
                          filterable
                          placeholder="请选择规格"
                          clearable
                          style="width:100%"
                          @change="handleShowSpecChange"
                        >
                          <el-option
                            v-for="dict in goodsSpecList"
                            :key="dict.id"
                            :label="dict.name"
                            :value="dict.id"
                            :disabled="dict.disabled">
                          </el-option>
                        </el-select>
                        
                      
                        <el-link :underline="false" slot="reference" type="primary">
                          <span style="font-size:12px;">添加规格</span>
                        </el-link>
                      </el-popover>
                    </el-row>
                  </el-tab-pane>
                </el-tabs>

                <el-tabs type="border-card" style="margin-top:20px">
                  <el-tab-pane label="商品SKU">
                    <div v-for="(sku, index) in dataForm.skus" :key="index" style="padding:20px 0px" class="border-buttom">
                      <el-row>
                        <el-form-item label="商品sku全称" :prop="'skus.' + index + '.skuName'"
                          :rules="[{ required: true, message:'商品sku全称不能为空', trigger: 'blur'}]">
                          <el-input
                            v-model="sku.skuName"
                            placeholder="请输入商品sku全称"
                          ></el-input>
                        </el-form-item>
                      </el-row>
                      <el-row>
                        <el-form-item label="商品sku简称" :prop="'skus.' + index + '.skuShortName'"
                          :rules="[{ required: true, message:'商品sku简称不能为空', trigger: 'blur'}]">
                          <el-input
                            v-model="sku.skuShortName"
                            placeholder="请输入商品sku简称"
                            maxlength="6"
                          ></el-input>
                        </el-form-item>
                      </el-row>
                      <el-row>
                        <el-form-item label="罐装数量" :prop="'skus.' + index + '.canningCount'"
                          :rules="[{ required: true, validator:validatorNumber, message:'罐装数量不能为空', trigger: 'blur'}]">
                          <el-input
                            v-model.number="sku.canningCount"
                            placeholder="请输入罐装数量"
                          ></el-input>
                        </el-form-item>
                      </el-row>
                      <el-row>
                        <el-form-item label="袋装数量" :prop="'skus.' + index + '.bagCount'"
                          :rules="[{ required: true, validator:validatorNumber, message:'袋装数量不能为空', trigger: 'blur'}]">
                          <el-input
                            v-model.number="sku.bagCount"
                            placeholder="请输入袋装数量"
                          ></el-input>
                        </el-form-item>
                      </el-row>
                      <el-row>
                        <el-form-item label="条装数量" :prop="'skus.' + index + '.stripCount'"
                          :rules="[{ required: true, validator:validatorNumber, message:'条装数量不能为空', trigger: 'blur'}]">
                          <el-input
                            v-model.number="sku.stripCount"
                            placeholder="请输入条装数量"
                          ></el-input>
                        </el-form-item>
                      </el-row>

                      <el-row>
                        <el-form-item label="积分策略" :prop="'skus.' + index + '.pointPolicyId'">
                          <el-select
                            v-model="sku.pointPolicyId"
                            filterable
                            placeholder="请选择积分策略"
                            clearable
                            style="width:100%"
                          >
                            <el-option
                              v-for="dict in pointPolicyList"
                              :key="dict.id"
                              :label="dict.policyName"
                              :value="dict.id"
                            />
                          </el-select>
                        </el-form-item>
                      </el-row>

                      <el-row>
                        <el-form-item label="sku轮播图" :prop="'skus.' + index + '.bannerImages'" 
                          :rules="[{ required: true, message:'sku轮播图不能为空', trigger: 'blur'}]">
                          <ImagesUpload v-model="sku.bannerImages"></ImagesUpload>
                          <span style="color:#FF0000">轮播图第一张为商品主图</span>
                        </el-form-item>
                      </el-row>
                      <el-row>
                        <el-form-item label="sku详情图" :prop="'skus.' + index + '.detailImages'" 
                          :rules="[{ required: true, message:'sku详情图不能为空', trigger: 'blur'}]">
                          <ImagesUpload v-model="sku.detailImages"></ImagesUpload>
                        </el-form-item>
                      </el-row>
                      
                      <el-table :data="[sku]" border style="width: 100%">
                        <el-table-column align="center" v-for="(spuSpec, index1) in goodsSpuSpecList" :key="index1" :label="spuSpec.value">
                          <template slot-scope="{row}">
                            <div v-for="(spec,index3) in row.specs" :key="index3">
                              <span v-if="spuSpec.specId == spec.specId">{{spec.specValueName}}</span>
                            </div>
                          </template>
                        </el-table-column>
                        
                        <el-table-column
                          align="center">
                          <template slot="header">
                            <span class="required-table-column">*</span>
                            <span>销售价格</span>
                          </template>  
                          <template slot-scope="{row}">
                            <el-form-item label="" :prop="'skus.' + index + '.sellPrice'" label-width="0"
                              :rules="[{ required: true, validator:validatorMoney, trigger: 'blur'}]" style="margin-top:18px">
                              <el-input v-model.number="row.sellPrice" placeholder="请输入销售价格" ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column
                          align="center">
                          <template slot="header">
                            <span class="required-table-column">*</span>
                            <span>市场价格</span>
                          </template>  
                          <template slot-scope="{row}">
                            <!-- <el-input v-model="row.marketPrice" placeholder="请输入市场价格" ></el-input> -->
                            <el-form-item label="" :prop="'skus.' + index + '.marketPrice'" label-width="0" 
                              :rules="[{ required: true, validator:validatorMoney, trigger: 'blur'}]" style="margin-top:18px">
                              <el-input v-model.number="row.marketPrice" placeholder="请输入市场价格" ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column
                          align="center">
                          <template slot="header">
                            <span class="required-table-column">*</span>
                            <span>虚拟销量</span>
                          </template> 
                          <template slot-scope="{row}">
                            <!-- <el-input v-model="row.virtualSales" placeholder="请输入虚拟销量" ></el-input> -->
                            <el-form-item label="" :prop="'skus.' + index + '.virtualSales'" label-width="0" 
                              :rules="[{ required: true, validator:validatorNumber, trigger: 'blur'}]" style="margin-top:18px">
                              <el-input v-model.number="row.virtualSales" placeholder="请输入虚拟销量" ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <!-- <el-table-column
                          align="center">
                          <template slot="header">
                            <span class="required-table-column">*</span>
                            <span>获取积分</span>
                          </template> 
                          <template slot-scope="{row}">
                            <el-form-item label="" :prop="'skus.' + index + '.point'" label-width="0" 
                              :rules="[{ required: true, validator:validatorNumber, trigger: 'blur'}]" style="margin-top:18px">
                              <el-input v-model.number="row.point" placeholder="请输入获取积分" ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column> -->
                        <!-- <el-table-column
                          align="center">
                          <template slot="header">
                            <span class="required-table-column">*</span>
                            <span>一级分润</span>
                          </template> 
                          <template slot-scope="{row}">
                            <el-form-item label="" :prop="'skus.' + index + '.firstProfit'" label-width="0"
                              :rules="[{ required: true, validator:validatorMoney, trigger: 'blur'}]" style="margin-top:18px">
                              <el-input v-model.number="row.firstProfit" placeholder="请输入一级分润" ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column> -->
                        <!-- <el-table-column
                          align="center">
                          <template slot="header">
                            <span class="required-table-column">*</span>
                            <span>二级分润</span>
                          </template> 
                          <template slot-scope="{row}">
                            <el-form-item label="" :prop="'skus.' + index + '.secondProfit'" label-width="0"
                              :rules="[{ required: true, validator:validatorMoney, trigger: 'blur'}]" style="margin-top:18px">
                              <el-input v-model.number="row.secondProfit" placeholder="请输入二级分润" ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column> -->
                        <el-table-column
                          label="首页一级推荐"
                          align="center">
                          <template slot-scope="{row}">
                            <!-- <el-switch v-model="row.hasMain" active-value="1" inactive-value="0"></el-switch> -->
                            <el-form-item label="" :prop="'skus.' + index + '.hasMain'" label-width="0" style="margin-top:18px">
                              <el-switch v-model="row.hasMain" active-value="1" inactive-value="0"></el-switch>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="首页二级推荐"
                          align="center">
                          <template slot-scope="{row}">
                            <!-- <el-switch v-model="row.hasSubMain" active-value="1" inactive-value="0"></el-switch> -->
                            <el-form-item label="" :prop="'skus.' + index + '.hasSubMain'" label-width="0" style="margin-top:18px">
                              <el-switch v-model="row.hasSubMain" active-value="1" inactive-value="0"></el-switch>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="推荐列表"
                          align="center">
                          <template slot-scope="{row}">
                            <!-- <el-switch v-model="row.hasRecommend" active-value="1" inactive-value="0"></el-switch> -->
                            <el-form-item label="" :prop="'skus.' + index + '.hasRecommend'" label-width="0" style="margin-top:18px">
                              <el-switch v-model="row.hasRecommend" active-value="1" inactive-value="0"></el-switch>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="上架状态"
                          align="center">
                          <template slot-scope="{row}">
                            <!-- <el-switch v-model="row.status" active-value="1" inactive-value="0" @change="handleChangeSkuStatus"></el-switch> -->
                            <el-form-item label="" :prop="'skus.' + index + '.status'" label-width="0" style="margin-top:18px">
                              <el-switch v-model="row.status" active-value="1" inactive-value="0" @change="handleSkuStatusChange"></el-switch>
                            </el-form-item>
                          </template>
                        </el-table-column>
                      </el-table>

                      <div style="margin-top:20px">
                        <el-row type="flex" justify="center">
                          <el-button
                            icon="el-icon-plus"
                            type="primary"
                            @click="handleAddSkuGift(sku)"
                            >添加赠品</el-button>
                        </el-row>

                        <el-table :data="sku.gifts" border style="width: 100%; margin-top:10px" v-if="sku.gifts.length > 0">
                          <el-table-column
                            align="center">
                            <template slot="header">
                              <span class="required-table-column">*</span>
                              <span>赠品展示图</span>
                            </template> 
                            <template slot-scope="scope">
                              <el-form-item label="" :prop="'skus.' + index + '.gifts.' + scope.$index +  '.coverImage'" label-width="20" 
                                :rules="[{ required: true, message: '赠品展示图必须选择，不能为空', trigger: 'blur'}]" style="margin-top:18px">
                                <ImageUploadSingle v-model="scope.row.coverImage"></ImageUploadSingle>
                              </el-form-item>
                            </template>
                          </el-table-column>
                          <el-table-column
                            label="赠品名称"
                            align="center"
                            prop="giftName">
                          </el-table-column>
                          <el-table-column
                            header-align="center"
                            align="center"
                            label="赠品图片">
                            <template slot-scope="scope">
                              <el-image
                                style="width: 67px; height: 67px"
                                :src="getGiftCover(scope.row.bannerImages)"
                                :preview-src-list="[getGiftCover(scope.row.bannerImages)]">
                              </el-image>
                            </template>
                          </el-table-column>
                          <el-table-column
                            align="center">
                            <template slot="header">
                              <span class="required-table-column">*</span>
                              <span>赠送数量（默认一个）</span>
                            </template> 
                            <template slot-scope="scope">
                              <!-- <el-input v-model="row.count" placeholder="请输入赠送数量" ></el-input> -->
                              <el-form-item label="" :prop="'skus.' + index + '.gifts.' + scope.$index +  '.count'" label-width="0" 
                                :rules="[{ required: true, validator:validatorNumber, trigger: 'blur'}]" style="margin-top:18px">
                                <el-input v-model.number="scope.row.count" placeholder="请输入赠送数量" ></el-input>
                              </el-form-item>
                            </template>
                          </el-table-column>

                          <el-table-column header-align="center" align="center" label="操作">
                            <template slot-scope="scope">
                              <el-button
                                type="text"
                                size="small"
                                icon="el-icon-delete"
                                @click="handleDeleteGift(sku,scope.row.id)"
                                >删除</el-button
                              >
                            </template>
                          </el-table-column>
                        </el-table>
                      </div>
                      
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </el-collapse-item>
            <!-- <el-collapse-item title="效率 Efficiency" name="3">
              <div>简化流程：设计简洁直观的操作流程；</div>
              <div>清晰明确：语言表达清晰且表意明确，让用户快速理解进而作出决策；</div>
              <div>帮助用户识别：界面简单直白，让用户快速识别而非回忆，减少用户记忆负担。</div>
            </el-collapse-item>
            <el-collapse-item title="可控 Controllability" name="4">
              <div>用户决策：根据场景可给予用户操作建议或安全提示，但不能代替用户进行决策；</div>
              <div>结果可控：用户可以自由的进行操作，包括撤销、回退和终止当前操作等。</div>
            </el-collapse-item> -->
          </el-collapse>
        </el-form>
      </div>
      <div class="dialog__footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-drawer>

    <GiftsForm  
        v-if="giftsFormVisible"
        ref="giftsForm"
        :visible.sync="giftsFormVisible">
    </GiftsForm>
  </div>
</template>

<script>
import { getObj, addObj, putObj } from "@/api/shop/goods/spu";
import ImagesUpload from "@/components/imagesUpload";
import { goodsBrandList } from "@/api/shop/goods/brand";
import {getGoodsSpecList} from '@/api/shop/goods/spec';
import GiftsForm from './gifts.vue';
import ImageUploadSingle from '@/components/imageUploadSingle';
import {getGoodsServerList} from '@/api/shop/config/server';
import {goodsLabelList} from '@/api/shop/goods/label';
import {getPointPolicyList} from '@/api/platform/point_policy';

export default {
  props:{
    visible: {
      type: Boolean,
      default: false
    },
  },
  watch:{

  },
  data() {
    return {
      activeNames:['1', '2', '3', '4'],
      canSubmit: false,
      dataForm: {
        skus:[],
        goodsServerIds:[],
        goodsLabelIds:[]
      },
      dataRule: {
        spuTitle: [
          { required: true, message: "商品标题不能为空", trigger: "blur" },
        ],
        brandId: [
          { required: true, message: "品牌名称不能为空", trigger: "blur" },
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" },
        ],
        spuType:[
        { required: true, message: "商品类型不能为空", trigger: "blur" },
        ]
      },
      // 品牌列表
      brandList:[],
      // 商品规格列表
      goodsSpecList:[],
      // 保障服务
      goodsServerList:[],
      // 是否显示规格下拉框
      isShowSpec:false,
      // 商品和规格对应关系
      goodsSpuSpecList:[],
      // 商品标签
      goodsLabelList:[],
      // 备份sku
      backupSkus:[],
      // 积分策略列表
      pointPolicyList:[],

      selectedSpec:'',
      selectedSpecValue:'',
      giftsFormVisible:false
    };
  },
  components: {
    ImagesUpload,
    GiftsForm,
    ImageUploadSingle
  },
  methods: {
    init(id) {
      this.canSubmit = true;
      // 获取品牌列表
      this.getBrandList()
      // 获取商品规格
      this.getGoodsSpecList(null)
      // 获取保障服务
      this.getGoodsServerList()
      // 获取商品标签
      this.getGoodsLabelList()
      // 获取积分策略
      this.getPointPolicyList()
      if(id){
        getObj(id).then((response) => {
          this.dataForm = response.data.data;
          this.dataForm.spuSpec.forEach(item=>{
            item.leaf = JSON.parse(item.leaf)
            this.goodsSpuSpecList.push(item)
          })

          this.dataForm.skus.forEach(sku=>{
            // sku.bannerImages = sku.bannerImages.split(',')
            // sku.detailImages = sku.detailImages.split(',')

            sku.bannerImages = sku.bannerImages ? JSON.parse(sku.bannerImages) : []
            sku.detailImages = sku.detailImages ? JSON.parse(sku.detailImages) : []

            // 销售价格转元
            sku.sellPrice = this.formatMoneyToYuan(sku.sellPrice)
            // 市场价格转分
            sku.marketPrice = this.formatMoneyToYuan(sku.marketPrice)
            // 一级分润转分
            sku.firstProfit = this.formatMoneyToYuan(sku.firstProfit)
            // 二级分润转分
            sku.secondProfit = this.formatMoneyToYuan(sku.secondProfit)

            sku.gifts.forEach(gift=>{
              if(gift.coverImage){
                let arr = JSON.parse(gift.coverImage)
                if(arr.length > 0){
                  gift.coverImage = arr[0]
                }
              }
            })
          })

          this.dataForm.goodsServerIds = this.dataForm.goodsServerIds ? this.dataForm.goodsServerIds.split(',') : []
          this.dataForm.goodsLabelIds = this.dataForm.goodsLabelIds ? this.dataForm.goodsLabelIds.split(',') : []

          console.log(this.dataForm)
        });
      }

      //console.log(this.cartesian([[1,2], [3]])) 
    },

    /**
     * 获取所有品牌
     */
    getBrandList(){
      goodsBrandList().then(res=>{
        this.brandList = res.data.data
      })
    },

    /**
     * 获取商品规格
     */
    getGoodsSpecList(){
      getGoodsSpecList().then(res=>{
        this.goodsSpecList = res.data.data
        this.goodsSpecList.forEach(item=>{
          this.$set(item, 'disabled', false)
        })
      })
    },

    /**
     * 获取保障服务
     */
    getGoodsServerList(){
      getGoodsServerList().then(res=>{
        this.goodsServerList = res.data.data
      })
    },

    /**
     * 获取商品标签
     */
    getGoodsLabelList(){
      goodsLabelList().then(res=>{
        this.goodsLabelList = res.data.data
      })
    },

    /**
     * 获取积分策略列表
     */
    getPointPolicyList(){
      getPointPolicyList().then(res=>{
        this.pointPolicyList = res.data.data
      })
    },

    /**
     * 选择商品规格
     */
    handleShowSpecChange(val){
      let data = this.goodsSpecList.filter(p=>p.id == val)
      if(data.length > 0){
        this.goodsSpuSpecList.push({
          spuId:this.dataForm.spuId,
          specId:data[0].id,
          value:data[0].name,
          leaf:[],
          isShowSpecValue:false
        })
        data[0].disabled = true
      }
      // 清空选择的规格
      this.selectedSpec = ''
    },

    /**
     * 获取对应规格的规格值
     */
    handleShowSpecValue(spec){
      getGoodsSpecList({
        specId: spec.specId
      }).then(res=>{
        if(!spec.hasOwnProperty('goodsSpecValueList')){
          this.$set(spec, 'goodsSpecValueList', [])
        }
        spec.goodsSpecValueList = res.data.data
        spec.goodsSpecValueList.forEach(item=>{
          if(!item.hasOwnProperty('disabled')){
            this.$set(item, 'disabled', false)
          }
          // 判断当前规格值是否选择
          let data = spec.leaf.filter(p=>p.id == item.id)
          if(data.length > 0){
            // 用户已经选择规格值
            item.disabled = true
          } else {
            item.disabled = false
          }          
        })
      })
    },

    /**
     * 选择规则值
     */
    handleShowSpecValueChange(spec, val){
      let data = spec.goodsSpecValueList.filter(p=>p.id == val)
      if(data.length > 0){
        spec.leaf.push({
          id: data[0].id,
          value: data[0].name
        })
        // 设置sku
        this.formatSku()
        data[0].disabled = true
      }
      // 清空选择的规格值
      this.selectedSpecValue = ''
    },

    /**
     * 修改sku
     */
    formatSku(){
      let specs = []
      // 获取规格
      this.goodsSpuSpecList.forEach(spec=>{
        let items = []
        spec.leaf.forEach(item=>{
          items.push({
            spuId: spec.spuId,
            specId: spec.specId,
            specValueId:item.id,
            specValueName: item.value
          })
        })
        if(items.length > 0){
          specs.push(items)
        }
      })
      // 获取规格笛卡尔积
      let newSpecList = this.cartesian(specs)
      this.backupSkus = this.dataForm.skus
      this.dataForm.skus = []
      console.log(this.backupSkus)
      newSpecList.forEach(specs=>{
        this.addSku(specs)
      })
    },

    /**
     * 新增SKU
     */
    addSku(specs){
      debugger
      let isSame = false
      // 判断备份的是否存在相同的规格
      for(let i = 0; i < this.backupSkus.length; i++){
        let oldSpecs = this.backupSkus[i].specs

        // 规格个数不同的场合
        if(specs instanceof Array){
          if(specs.length != oldSpecs.length){
            continue
          }
        }
        

        let sameCount = 0
        // 判断是否全匹配
        for(let j = 0; j < oldSpecs.length; j++){
          let oldSpec = oldSpecs[j]
          if(specs instanceof Array){
            let arr = specs.filter(p=>p.specId === oldSpec.specId && p.specValueId === oldSpec.specValueId)
            if(arr.length > 0){
              sameCount++
            }  
          } else {
            if(oldSpec.specId === specs.specId && oldSpec.specValueId === specs.specValueId){
              sameCount++
            }
          }
        }

        if(sameCount == oldSpecs.length){
          isSame = true
          this.dataForm.skus.push(this.backupSkus[i])
          break;
        }
        
      }

      // 存在相同项，不添加
      if(isSame)
        return

      let data = {}
      data.spuId = ''
      data.skuName = ''
      data.skuShortName = ''
      data.canningCount = 0
      data.bagCount = 0
      data.stripCount = 0
      data.bannerImages = []
      data.detailImages = []
      data.sellPrice = 0
      data.marketPrice = 0
      data.basePrice = 0
      data.unit = 0
      // 默认上架
      data.status = '1'
      data.virtualSales = 0
      data.hasMain = '0'
      data.hasSubMain = '0'
      data.hasRecommend = '0'
      //data.point = 0
      data.pointPolicyId = ''
      data.firstProfitPolicyId = ''
      data.secondProfitPolicyId = ''
      data.sort = 1
      if(specs instanceof Array){
        data.specs = specs
      } else {
        data.specs = []
        data.specs.push(specs)
      }

      data.gifts=[]
      this.dataForm.status = '1'
      this.dataForm.skus.push(data)
    },

    /*
    * @Author: Mr Jiang.Xu 
    * @Date: 2019-08-31 00:05:33 
    * @Last Modified by:   Mr Jiang.Xu 
    * @Last Modified time: 2019-08-31 00:05:33 
    */
    cartesian(arr) {
      if (arr.length < 2) return arr[0] || [];
      return [].reduce.call(arr, function (col, set) {
        let res = [];
        col.forEach(c => {
          set.forEach(s => {
            let t = [].concat(Array.isArray(c) ? c : [c]);
            t.push(s);
            res.push(t);
          })
        });
        return res;
      });      
    },

    /**
     * 删除规格
     */
    handleDelSpec(spec){
      for(let i = 0;i<this.goodsSpuSpecList.length;i++){
        if(this.goodsSpuSpecList[i].specId == spec.specId){
          this.goodsSpuSpecList.splice(i,1)

          let data = this.goodsSpecList.filter(p=>p.id == spec.specId)
          if(data.length > 0){
            data[0].disabled = false
          }

          break;
        }
      }
      this.formatSku()
      // 删除sku，判断产品上架状态
      this.handleChangeSkuStatus()
    },

    /**
     * 删除规格值
     */
    handleTagClose(spec, tag){
      for(let i = 0; i < spec.leaf.length; i++){
        if(spec.leaf[i].id == tag.id){
          spec.leaf.splice(i,1)
          break;
        }
      }
      this.formatSku()
    },

    //重置表单
    closeDialog() {
      this.$emit('update:visible', false)
    },

    /**
     * 提交
     */
    handleSubmit(){
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          const msg = this.checkData()
          if(msg != ''){
            this.$message.error(msg)
            return
          }
          
          let submitData = JSON.parse(JSON.stringify(this.dataForm))
          submitData.skus.forEach(sku=>{
            sku.bannerImages = sku.bannerImages.map(p=>p.materialId).join()
            sku.detailImages = sku.detailImages.map(p=>p.materialId).join()
            // 销售价格转分
            sku.sellPrice = this.formatMoneyToFen(sku.sellPrice)
            // 市场价格转分
            sku.marketPrice = this.formatMoneyToFen(sku.marketPrice)
            // 一级分润转分
            //sku.firstProfit = this.formatMoneyToFen(sku.firstProfit)
            // 二级分润转分
            //sku.secondProfit = this.formatMoneyToFen(sku.secondProfit)

            sku.gifts.forEach(gift=>{
              delete gift.bannerImages
              gift.coverImage = gift.coverImage.materialId
            })
          })
          
          submitData.spuSpec = []
          this.goodsSpuSpecList.forEach(spec=>{
            submitData.spuSpec.push({
              spuId: spec.spuId,
              specId: spec.specId,
              leaf: JSON.stringify(spec.leaf)
            })
          })

          // 保障服务Ids
          if(submitData.goodsServerIds.length > 0){
            submitData.goodsServerIds = submitData.goodsServerIds.join()
          } else {
            submitData.goodsServerIds = ''
          }

          // 商品标签Ids
          if(submitData.goodsLabelIds.length > 0){
            submitData.goodsLabelIds = submitData.goodsLabelIds.join()
          } else {
            submitData.goodsLabelIds = ''
          }
          
          if(submitData.id){
            putObj(submitData).then((data) => {
              this.$notify.success("修改成功");
              this.$emit("refreshDataList");
              this.closeDialog()
            }).catch(() => {
              this.canSubmit = true;
            });
          } else {
            console.log(submitData)
            addObj(submitData).then((data) => {
              this.$notify.success("添加成功");
              this.$emit("refreshDataList");
              this.closeDialog()
            }).catch(() => {
              this.canSubmit = true;
            });
          }
          
        }
      })
      
    },

    /**
     * 检查数据完整性
     */
    checkData(){
      if(this.dataForm.skus.length <= 0){
        return '请添加商品sku'
      }
      return ''
    },

    /**
     * sku添加赠品
     */
    handleAddSkuGift(sku){
      this.giftsFormVisible = true
      this.$nextTick(() => {
        this.$refs.giftsForm.init(sku);
      });
    },

    /**
     * 删除SKU的赠品
     */
    handleDeleteGift(sku, giftId){
      for(let i = 0; i < sku.gifts.length; i++){
        if(sku.gifts[i].id == giftId){
          sku.gifts.splice(i,1)
          break;
        }
      }
    },

    /**
     * 改变商品状态
     */
    handleChangeGoodsSpuStatus(val){
      this.dataForm.skus.forEach(sku=>{
        sku.status = val
      })
    },

    /**
     * 改变sku上架状态
     */
    handleSkuStatusChange(){
      // 获取所有sku状态
      let arr = this.dataForm.skus.filter(p=>p.status == "1")
      if(arr.length <= 0){
        this.dataForm.status = "0"
      } else {
        this.dataForm.status = "1"
      }
    },

    /**
     * 改变其中一个sku上架状态
     */
    handleChangeSkuStatus(){
      let sum = 0
      this.dataForm.skus.forEach(sku=>{
        if(sku.status == '1'){
          sum++
        }
      })
      this.dataForm.status = sum > 0 ? '1' : '0'
    },

    /**
     * 获得主图
     */
    getGiftCover(item){
      if(item){
        let images = JSON.parse(item)
        if(images.length > 0){
          return images[0].materialUrl
        } else {
          return ''
        }
      } else {
        return ''
      }

      // let images = item ? item.split(',') : []
      // if(images.length > 0){
      //   return images[0]
      // } else {
      //   return ''
      // }
    },

    /**
     * 验证金额
     */
    validatorMoney (rule, value, callback)  {
      if(value === ''){
        let field = ''
        // if(rule.field.indexOf('sellPrice') > 0){
        //   field = '销售价格'
        // } else if(rule.field.indexOf('marketPrice') > 0){
        //   field = '市场价格'
        // } else if(rule.field.indexOf('firstProfit') > 0){
        //   field = '一级分润'
        // } else if(rule.field.indexOf('secondProfit') > 0){
        //   field = '二级分润'
        // }
        callback(new Error(`${field}不能为空`))
      } else {
        callback()
      }
    },

    /**
     * 验证数字
     */
    validatorNumber(rule, value, callback){
      if(value === ''){
        let field = ''
        // if(rule.field.indexOf('virtualSales') > 0){
        //   field = '虚拟销量'
        // } else if(rule.field.indexOf('point') > 0){
        //   field = '积分'
        // }
        callback(new Error(`${field}不能为空`))
      } else {
        callback()
      }
    }
  },
};
</script>

<style scoped>

.header-icon{
  font-size: 16px;
  margin-right: 10px;
}

.title-size{
  font-size: 16px;
}

.dialog__footer {
  display: block;
  padding: 10px 16px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border-top: 1px solid #f0f0f0;
  width: 100%;
  position: absolute;
  left: 0;
  bottom: 0;
  background-color: #fff;
  text-align: right;
}

.border-buttom{
  border-bottom: #cccccc solid 1px;
}

.required-table-column{
  margin-right:2px; color:#FF0000
}

/* .el-form-item{
    margin-bottom: 0px;
} */
</style>
